package com.wuxuehua.myapp.service;

import com.wuxuehua.myapp.domain.Authority;
import com.wuxuehua.myapp.domain.Shop;
import com.wuxuehua.myapp.domain.User;
import com.wuxuehua.myapp.repository.AuthorityRepository;
import com.wuxuehua.myapp.repository.ShopRepository;
import com.wuxuehua.myapp.repository.UserRepository;
import com.wuxuehua.myapp.security.AuthoritiesConstants;
import com.wuxuehua.myapp.security.SecurityUtils;
import org.activiti.engine.IdentityService;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.impl.identity.Authentication;
import org.activiti.engine.impl.persistence.entity.GroupEntity;
import org.activiti.engine.impl.persistence.entity.UserEntity;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.activiti.engine.task.TaskQuery;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * Created with IntelliJ IDEA.
 * User: 吴学华
 * Date: 17-10-18
 * Time: 下午3:46
 */
@Service
@Transactional
public class DingDanService {
    private final Logger log = LoggerFactory.getLogger(DingDanService.class);

    @Autowired
    RepositoryService repositoryService;

    @Autowired
    RuntimeService runtimeService;

    @Autowired
    IdentityService identityService;


    @Autowired
    TaskService taskService;

    @Autowired
    ShopRepository orderService;

    @Autowired
    UserService userService;

    @Autowired
    UserRepository userRepository;


    @Autowired
    AuthorityRepository authorityRepository;




    /**
     * 采购员提交
     * 流程开始
     *
     * @param orderId
     */
    public void commitOrder(Long orderId, Long currentUserId) {

        Shop one = orderService.findOne(orderId);
        Map<String, Object> map = new HashMap<>();
        map.put("create_order", currentUserId);//设定提交订单人　驳回后任务指定
        map.put("业务数据", one);
        String pdkey = "simple_dd";
        String businessKey = String.valueOf(orderId);//业务id
        ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(pdkey, businessKey, map);
        log.info("启动流程实例　：" + processInstance.getId() + " name: " + processInstance.getName());
        one.setStart(0);
    }

    /**
     * 查看组任务
     */
    public List<Task> findGroupTask(Long currentUserId) {
        TaskQuery query = taskService.createTaskQuery();
        String candidateUser = String.valueOf(currentUserId);
        query.taskCandidateUser(candidateUser);
        List<Task> list = query.list();
        return list;
    }

    /**
     * 拾取组任务
     */
    public void claimGroupTask(String taskId, Long currentUserId) {
        String userId = String.valueOf(currentUserId);
        taskService.claim(taskId, userId);
    }

    /**
     * 查看个人任务
     */
    public List<Task> findUserTask(Long currentUserId) {
        TaskQuery taskQuery = taskService.createTaskQuery();
        taskQuery.taskAssignee(String.valueOf(currentUserId));
        List<Task> list = taskQuery.list();
        return list;
    }

    /**
     * 根据taskid 获取订单id
     */
    public Shop getOrder(String taskId) {
        Task task = taskService.createTaskQuery().taskId(taskId).singleResult();
        String processInstanceId = task.getProcessInstanceId();
        ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();
        String businessKey = processInstance.getBusinessKey();
        Shop one = orderService.findOne(Long.valueOf(businessKey));
        return one;
    }


    /**
     * 采购经理提交审核
     */
    public void submitCheck(String taskId) {
        taskService.complete(taskId);
    }

    /**
     * 采购经理发送订单任务
     */
    public void sendOrder(String taskId) {
        taskService.complete(taskId);
    }

    /**
     * 商品出库
     */
    public void outStore(String taskId) {
        taskService.complete(taskId);
    }

    /**
     * 物流配送
     */
    public void transferGoods(String taskId) {
        taskService.complete(taskId);
    }

    /**
     * 企业确认收货
     */
    public void receive(String taskId) {
        taskService.complete(taskId);
    }

    /**
     * 供应商完成订单
     */
    public void completeOrder(String taskId) {
        taskService.complete(taskId);
    }


    /**
     * 排他网关审核任务
     *
     * @param taskId 　任务id
     * @param check  　是否通过　0否　１是
     * @param text   　审核说明
     */
    public void completeTask(String taskId, String check, String text, String checkKey) {
        Map<String, Object> map = new HashMap<>();
        map.put(SecurityUtils.getCurrentUserLogin(), text);
        map.put(checkKey, check);
        taskService.complete(taskId, map);
    }


    /**
     * 排他网关审核任务
     *
     * @param taskId
     * @param check
     * @param text
     */
    public void check(String taskId, String check, String text) {
        String login = SecurityUtils.getCurrentUserLogin();
        Optional<User> user = userService.getUserWithAuthoritiesByLogin(login);
        Set<Authority> authorities = user.get().getAuthorities();
        for (Authority a : authorities) {
            String name = a.getName();
            if (name.equals(AuthoritiesConstants.AUDIT_1)) {
                //一级审核
                completeTask(taskId, check, text, "result");
                break;
            }

            if (name.equals(AuthoritiesConstants.AUDIT_2)) {
                //二级审核
                completeTask(taskId, check, text, "result2");
                break;
            }

            if (name.equals(AuthoritiesConstants.SUPPLIER)) {
                //二级审核
                completeTask(taskId, check, text, "result3");
                break;
            }

        }
    }

    /**
     * 同步用户数据和角色数据到activiti的用户表和角色表中
     */
    public void synchronizedUserAndRole() {
        List<User> users = userRepository.findAll();
        List<Authority> roles = authorityRepository.findAll();
        for (User user : users) {
            Long id = user.getId();
            identityService.saveUser(new UserEntity(String.valueOf(id)));
        }

        for (Authority authority : roles) {
            String name = authority.getName();
            identityService.saveGroup(new GroupEntity(name));
        }

        for (User user : users) {
            Long id = user.getId();
            Set<Authority> authorities = user.getAuthorities();
            for (Authority authority : authorities) {
                String name = authority.getName();
                identityService.createMembership(String.valueOf(id),name);
            }
        }

    }


    public void test(){
    }


}
